package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.OrderInfoComponent;
import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.GoodsInfo;
import com.dy.lock.screen.pojo.OrderInfo;
import com.dy.lock.screen.pojo.ScoreInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.GoodsService;
import com.dy.lock.screen.service.OrderService;
import com.dy.lock.screen.service.ScoreService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.utils.DateUtil;
import com.dy.lock.screen.utils.IDGenerater;
import com.dy.lock.screen.vo.OrderVo;
import com.dy.lock.screen.vo.UserVo;
import com.google.gson.Gson;

@Component("orderInfoComponent")
public class OrderInfoComponentImpl implements OrderInfoComponent {
	private static final Logger log = Logger
			.getLogger(OrderInfoComponentImpl.class);
	private Gson gson;

	@Resource(name = "orderService")
	private OrderService orderService;
	@Resource(name = "scoreService")
	private ScoreService scoreService;
	@Resource(name = "goodsService")
	private GoodsService goodsService;

	public OrderInfoComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public boolean deleteOrderForm(String body, Head head) {
		OrderVo vo = gson.fromJson(body, OrderVo.class);
		if (vo != null) {
			OrderInfo info = new OrderInfo();
			info.setOrderId(vo.getOrderId());
			info.setIsDelete("0");
			info.setUpdateTime(new Date());
			int re = this.orderService.update(info, head);
			if (re > 0) {
				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",删除订单时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public boolean exchangeOrderForm(String body, Head head) {
		OrderVo vo = gson.fromJson(body, OrderVo.class);
		if (vo != null) {
			GoodsInfo goodsInfo = this.goodsService.queryByOrderId(vo
					.getOrderId());
			if (goodsInfo.getMerchantCode().equals(vo.getMerchantCode())) {
				OrderInfo info = new OrderInfo();
				info.setOrderId(vo.getOrderId());
				info.setUpdateTime(new Date());
				info.setExchangeTime(new Date());
				info.setOrderState(Constant.ORDER_STATUS_EXCHANGED);
				int re = this.orderService.update(info, head);
				if (re > 0) {
					return true;
				} else {
					throw new ServerDisponseException(
							TransmissionCode.OPERATOR_EXCEPTION.getCode(),
							TransmissionCode.OPERATOR_EXCEPTION.getMessage());
				}
			} else {
				log.info("requestId:" + head.getRequestId() + ",兑换商品时，商家码错误。");
				throw new ServerDisponseException(
						TransmissionCode.MERCHANT_CODE_ERROR.getCode(),
						TransmissionCode.MERCHANT_CODE_ERROR.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",兑换商品时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<OrderVo> list(String body, Head head) {
		OrderVo vo = gson.fromJson(body, OrderVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("pageStart", pageStart);
			paraMap.put("pageEnd", pageEnd);
			paraMap.put("isDelete", "1");
			paraMap.put("orderState", vo.getType());
			paraMap.put("userId", vo.getUserId());
			List<OrderInfo> orderInfoList = this.orderService.queryPage(
					paraMap, head);
			List<OrderVo> orderVoList = new ArrayList<OrderVo>();
			if (orderInfoList != null && !orderInfoList.isEmpty()) {
				for (OrderInfo info : orderInfoList) {
					OrderVo orderVo = new OrderVo();
					orderVo.setCreateTime(DateUtil.formatTime(info
							.getCreateOrderTime()));
					orderVo.setOrderId(info.getOrderId());
					orderVo.setName(info.getGoodsName());
					if (info.getGoodsPhotoPath() != null) {
						String photoUrl = info.getGoodsPhotoPath().split(";")[0];
						orderVo.setImageUrl(CommonUtil.getUrlPrefix()
								+ photoUrl);
					}
					if (info.getExchangeTime() != null) {
						orderVo.setExchangeTime(DateUtil.formatTime(info
								.getExchangeTime()));
						orderVo.setIsExchanged(true);
					}

					if (Constant.EXCHANGE_TYPE_GET_MYSELF.equals(info
							.getExchangeType())) {
						orderVo.setWay(Constant.EXCHANGE_TYPE_GET_MYSELF);
					}
					if (info.getEvaluate() > 0) {
						orderVo.setEvaluate(true);
					}
					orderVoList.add(orderVo);
				}
				return orderVoList;

			} else {
				return new ArrayList<OrderVo>();
			}

		} else {
			log.info("requestId:" + head.getRequestId() + ",获取订单列表时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public synchronized OrderVo pay(String body, Head head) {
		UserVo vo = gson.fromJson(body, UserVo.class);
		if (vo != null) {
			ScoreInfo score = this.scoreService.queryByPrimaryKey(vo
					.getUserId());
			GoodsInfo goods = this.goodsService.queryByPrimaryKey(vo
					.getGoodsId());
			if (score == null) {
				throw new ServerDisponseException(
						TransmissionCode.BALANCE_NOT_ENOUGH.getCode(),
						TransmissionCode.BALANCE_NOT_ENOUGH.getMessage());
			}
			if (goods != null && goods.getGoodsStock() <= 0) {
				throw new ServerDisponseException(
						TransmissionCode.GOODS_EXCHANGED_FINISH.getCode(),
						TransmissionCode.GOODS_EXCHANGED_FINISH.getMessage());
			}
			if (!CommonUtil.compare(score.getExchangedScore(), goods
					.getGoodsPrice().intValue())) {
				log.info("requestId:" + head.getRequestId() + ",用户付款时，余额不足。");
				throw new ServerDisponseException(
						TransmissionCode.BALANCE_NOT_ENOUGH.getCode(),
						TransmissionCode.BALANCE_NOT_ENOUGH.getMessage());
			}
			String orderNo = IDGenerater.getInstance().getOrderNo(
					"OrderInfoComponentImpl");
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setOrderId(orderNo);
			orderInfo.setCustomerId(vo.getUserId());
			orderInfo.setGoodsId(vo.getGoodsId());
			orderInfo.setGoodsName(goods.getGoodsName());
			orderInfo.setMerchantId(goods.getMerchantId());
			orderInfo.setGoodsNum(1);
			orderInfo.setGoodsPrice(goods.getGoodsPrice());
			orderInfo.setTotalPrice(goods.getGoodsPrice());
			orderInfo.setExchangeType(Constant.EXCHANGE_TYPE_GET_MYSELF);
			orderInfo.setIsDelete(Constant.IS_NOT_DELETE);
			orderInfo.setOrderState(Constant.ORDER_STATUS_NOT_EXCHANGED);
			orderInfo.setCreateOrderTime(new Date());
			// 购买商品后剩余的逗币积分
			int surplus = CommonUtil.sub(score.getExchangedScore(), goods
					.getGoodsPrice().intValue());
			int orderRe = this.orderService.save(orderInfo, goods, surplus,
					head);
			if (orderRe > 0) {
				OrderVo orVo = new OrderVo();
				orVo.setSurplus(surplus);
				orVo.setUserId(vo.getUserId());
				orVo.setOrderId(orderNo);
				return orVo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}

		} else {
			log.info("requestId:" + head.getRequestId() + ",用户付款时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public OrderVo exchangeSuccess(String body, Head head) {
		OrderVo orderVo = gson.fromJson(body, OrderVo.class);
		if (orderVo != null) {
			String orderNo = orderVo.getOrderNo();
			OrderInfo orderInfo = this.orderService.queryByPrimaryKey(orderNo);
			if (orderInfo != null) {
				OrderVo ovo = new OrderVo();
				ovo.setOrderNo(orderInfo.getOrderId());
				ovo.setCreateTime(DateUtil.formatTime(orderInfo
						.getCreateOrderTime()));
				ovo.setTotalPrice(orderInfo.getTotalPrice().intValue());
				ovo.setExchangeType(orderInfo.getExchangeType());
				return ovo;
			}

		} else {
			log.info("requestId:" + head.getRequestId() + ",兑换商品时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
		return null;
	}

	@Override
	public OrderVo getOrderForm(String body, Head head) {
		OrderVo vo = gson.fromJson(body, OrderVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getOrderId())) {
			String userId = vo.getUserId();
			OrderInfo info = this.orderService.getOrderDetail(vo.getOrderId(),
					userId);
			if (info != null) {
				OrderVo orderVo = new OrderVo();
				orderVo.setOrderId(info.getOrderId());
				orderVo.setTotalPrice(info.getTotalPrice().intValue());
				orderVo.setName(info.getGoodsName());
				if (info.getGoodsPhotoPath() != null) {
					String photoUrl = info.getGoodsPhotoPath().split(";")[0];
					orderVo.setUrl(CommonUtil.getUrlPrefix() + photoUrl);
				}
				if (Constant.EXCHANGE_TYPE_GET_MYSELF.equals(info
						.getExchangeType())) {
					orderVo.setWay(Constant.EXCHANGE_TYPE_GET_MYSELF);
				}
				orderVo.setAddress(info.getExchangeAddress());
				orderVo.setGoodsId(info.getGoodsId());

				if (info.getExchangeTime() != null) {
					orderVo.setExchangeTime(DateUtil.formatTime(info
							.getExchangeTime()));
					orderVo.setIsExchanged(true);
				}
				if (info.getCreateOrderTime() != null) {
					orderVo.setCreateTime(DateUtil.formatTime(info
							.getCreateOrderTime()));
				}
				if (info.getEvaluate() > 0) {
					orderVo.setEvaluate(true);
				}
				return orderVo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取订单详情时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}
}
